import React from 'react';
import { Button, Dropdown, Input, Space, Modal, message } from 'antd'
import { PlusOutlined, FolderAddOutlined } from '@ant-design/icons';
import { useDispatch } from 'react-redux';
import FolderMenu from './FolderMenu';
import { getStorageManager } from '@/file_storage'
import { getMacroFolderStructure } from '@/apps/panel/actions'
import { sanitizeFileName } from '@/common/utils'
import log from '@/common/log'
import './index.less';

export default function FolderSidebar() {

    const dispatch = useDispatch<any>();

    // 新建文件
    const macroCreateFile = ({ dir }: { dir: string; }) => {
        let macroName = 'untitled'
        Modal.confirm({
            title: '新建用例',
            // @ts-ignore
            content: <Input
                placeholder='用例名称'
                defaultValue={macroName}
                onChange={(e) => { macroName = e.target.value }} />,
            onOk: () => {
                const macroStorage = getStorageManager().getMacroStorage()
                const path = macroStorage.getPathLib()
                const filePath = path.join(dir, `${sanitizeFileName(macroName)}.json`)
                const fullPath = macroStorage.filePath(filePath)
                return macroStorage.fileExists(fullPath)
                    .then(exists => {
                        if (exists) {
                            const msg = `用例'${macroName}'已存在`
                            message.error(msg)
                            throw new Error(msg)
                        }

                        return macroStorage.write(filePath, {
                            name: macroName,
                            data: {
                                commands: []
                            }
                        })
                            .then(
                                () => {
                                    message.success(`用例'${macroName}'创建成功`)
                                    // 更新目录
                                    dispatch(getMacroFolderStructure())
                                    return true
                                },
                                (e: Error) => {
                                    log.error(e)
                                    const msg = '创建用例失败: ' + e.message
                                    message.error(msg)
                                    throw new Error(msg)
                                }
                            )
                    })
            }
        })
    }

    // 新建文件夹
    const macroCreateFolder = ({ dir }: { dir: string }) => {
        let folderName = 'untitled'
        Modal.confirm({
            title: '新建文件夹',
            // @ts-ignore
            content: <Input
                placeholder='用例名称'
                defaultValue={folderName}
                onChange={(e) => { folderName = e.target.value }} />,
            onOk: () => {
                const macroStorage = getStorageManager().getMacroStorage()
                const path = macroStorage.getPathLib()
                const parentDir = macroStorage.dirPath(dir)
                const newFullPath = path.join(parentDir, sanitizeFileName(folderName))
                return macroStorage.directoryExists(newFullPath)
                    .then(exists => {
                        if (exists) {
                            const msg = `文件夹'${folderName}'已存在`
                            message.error(msg)
                            throw new Error(msg)
                        }

                        return getStorageManager().getMacroStorage().createDirectory(
                            newFullPath
                        ).then(
                            () => {
                                message.success(`新建文件夹'${folderName}'成功`)
                                dispatch(getMacroFolderStructure())
                                return true
                            },
                            (e) => {
                                log.error(e)
                                const msg = '新建文件夹失败: ' + e.message
                                message.error(msg)
                                throw new Error(msg)
                            }
                        )
                    })
            }
        })
    }

    return (
        <div className='floder-sidebar'  >
            {/* @ts-ignore */}
            <Space style={{ padding: '10px' }}>
                {/* @ts-ignore */}
                <Button
                    //  @ts-ignore
                    icon={<PlusOutlined />}
                    type='primary'
                    onClick={() => {
                        macroCreateFile({ dir: '/' })
                    }}
                >
                    新建用例
                </Button>
                {/* @ts-ignore */}
                <Dropdown
                    menu={{
                        items: [
                            {
                                key: 'new_macro_folder',
                                label: '新建文件夹',
                                onClick: () => {
                                    macroCreateFolder({ dir: '/' })
                                }
                            },
                            {
                                key: 'import_json',
                                label: '导入JSON或ZIP',
                                onClick: () => {

                                }
                            }
                        ]
                    }}
                    trigger={['click']}
                >
                    {/* @ts-ignore */}
                    <Button icon={<FolderAddOutlined />}>文件</Button>
                </Dropdown>
            </Space>
            {/* @ts-ignore */}
            <Space style={{ padding: '10px' }}>
                {/* @ts-ignore */}
                <Input.Search
                    placeholder="搜索"
                    allowClear
                />
            </Space>
            <FolderMenu macroCreateFile={macroCreateFile} macroCreateFolder={macroCreateFolder} />
        </div>
    )
}